'use strict';

/* Controllers */
function opentokCtrl($scope,$stateParams,$http,$location, $rootScope, uploadManager) {
	nexus.openTokScope = $scope;
	nexus.openTokScope.id = $stateParams.id;
	var notes;
	var sessionUserList = new Firebase('https://adviseme.firebaseio.com/counselSessions/'+nexus.openTokScope.id+'/users/');;
	$http.get( $stateParams.id+'/startSession').success(function(data) {
    $scope.openTokData = data;
    if(data != null && data != 'undefined'){
		
		if (TB.checkSystemRequirements() != TB.HAS_REQUIREMENTS) {
			alert("You don't have the minimum requirements to run this application."
					+ "Please upgrade to the latest version of Flash.");
		} else {
			 $scope.session = TB.initSession(data.sessionId); // Initialize session
			 
			 $scope.session.addEventListener('sessionConnected', sessionConnectedHandler);
			 $scope.session.addEventListener('streamCreated', streamCreatedHandler);
		     TB.addEventListener("exception", exceptionHandler);
		     TB.setLogLevel(TB.DEBUG);
		     $scope.session.connect(data.apiKey, data.moderatorToken);
		}
		notes=new Firebase('https://adviseme.firebaseio.com/counselSessions/'+nexus.openTokScope.id+'/notes/'+$scope.openTokData.userName);
	}
   });
	
	$scope.uploadedFiles = [];
	$scope.newMsg = "";
	
	$scope.newNote = "";
	var firebaseFiles=new Firebase('https://adviseme.firebaseio.com/counselSessions/'+nexus.openTokScope.id+'/files/');
	var chatBox=new Firebase('https://adviseme.firebaseio.com/counselSessions/'+nexus.openTokScope.id+'/chatBox');
	
	//For chat related stuff
	$scope.sendMessage = function (){
		var pushMsg=chatBox.push();
		pushMsg.set({name:$scope.openTokData.userName, msg:$scope.newMsg})
		$scope.newMsg = ""; 
		
	};
	
	 sessionUserList.on('value', function(data){
	 		var fireBaseUserList = data.val();
	 		$scope.userList = [];
	 		for(var user in fireBaseUserList){
	 			$scope.userList.push(fireBaseUserList[user]);
	         }
	 		$scope.$apply();
	 		if($.inArray($scope.openTokData.userName,$scope.userList) == -1){
	 			$rootScope.$broadcast('userJoined');
	 		}
	 	})
	 	
	chatBox.on('value', function(data) {
		var template = '';
		data.forEach(function(data) {
			var msg = data.val()
			
			template += msg['name'] + ' : ' + msg['msg'] + '\n';
				
			
		})
		$('#displayChat textarea').text(template)
		
	})
	
	
	$rootScope.$on('userJoined', function(){
		sessionUserList.push($scope.openTokData.userName);
    })
    
	firebaseFiles.on('value', function(data){
		var firebasefileslist = data.val();
		$scope.uploadedFiles = [];
		for(var file in firebasefileslist){
			$scope.uploadedFiles.push(firebasefileslist[file]);
        }
		$scope.$apply();
	})
	
	/********** File Uploading part ***************/
	$scope.files = [];
    $scope.percentage = 0;

    $scope.upload = function () {
        uploadManager.upload();
        $scope.files = [];
    };
 

    $rootScope.$on('fileAdded', function (e, call) {
        $scope.files.push(call);
        $scope.$apply();
    });

    $rootScope.$on('uploadProgress', function (e, call) {
        $scope.percentage = call;
        $scope.$apply();
    });
	  
	/***************** File uploading part finished *************/
    
	$scope.stopSession=function(){
		
		/*var noteMsg=notes.push()
		noteMsg.set({notes:$scope.newNote})*/
		$scope.unpublish($scope.publisher);
		$scope.disconnectSession();
		$http.get( nexus.openTokScope.id+'/stopSession').success(function(data) {
			data = eval(data);
			if(data == 'dashboard'){
				$location.url('dashboard/feed');
			}else{
				$location.url('/user/'+nexus.openTokScope.id+'/'+data);
			}
	});
	}
	
	var archive;
	
	$scope.archiveCreateHandler=function(event){
        archive = event.archives[0];
	}
       
	function sessionConnectedHandler(event){
		subscribeToStreams(event.streams);
			 //var publishProps = {height:320, width:320};
			
		      //$scope.publisher = TB.initPublisher($scope.openTokData.apiKey, 'temp_pub_div');
		      // Send my stream to the session
			 if($scope.openTokData.oneToMany){
				 //If session is one to many publish only if logged in user is expert
				 if($scope.openTokData.expert){
					 $("#publisherDiv").append("<div id='temp_pub_div' ></div>");
					 $scope.publisher = TB.initPublisher($scope.openTokData.apiKey, 'temp_pub_div');
					 $scope.session.publish($scope.publisher);
				 }
			 }else{
				 //Publish if session is not one to many
				 $("#publisherDiv").append("<div id='temp_pub_div' ></div>");
				 $scope.publisher = TB.initPublisher($scope.openTokData.apiKey, 'temp_pub_div');
				 $scope.session.publish($scope.publisher);
			 }
		      $('#startBtn').text("Stop Teaching");
			  $("#startBtn").attr('onclick','disconnectSession();');
			 //changeStatusBtnToStartRecording();
			 //
 	}
	
	function streamCreatedHandler(event) {
	      // Subscribe to any new streams that are created
	      subscribeToStreams(event.streams);
	    }

	$scope.changeStatusBtnToStartRecording=function(){
		$("#recordBtn").attr("class","btn");
	      $('#recordBtn').text('Start Recording');
	      $("#recordBtn").attr('onclick','startRecording();');
	      $("#recordBtn").attr("href", '#');

	}
	
	$scope.changeStatusToStopRecording=function(){
		  $('#recordBtn').text('Stop Recording');
	      $("#recordBtn").attr('onclick','stopRecording();');
	      $("#recordBtn").attr("href", '#');		
	}
	
	$scope.stopRecording=function(){
		$scope.session.stopRecording(archive);
		changeStatusBtnToStartRecording()
	}
	
	$scope.recordingInProgressHandler=function(event){
	    alert("There is a recording in progress already.");
	}

	$scope.recordingStartedHandler=function(event){
	    alert("The session is being recorded.");
	}
	
	$scope.disconnectSession=function(){
		$scope.session.disconnect();
	}
	
	$scope.unpublish=function(publisher){
		$scope.session.unpublish(publisher);
	}
	
	function subscribeToStreams(streams){
		for (var i = 0; i < streams.length; i++) {
			if (streams[i].connection.connectionId == $scope.session.connection.connectionId) {
				//return;
			}else{
				if($scope.openTokData.oneToMany){
					//If session is one to many and if logged in user is not expert, subscribe to video and display 
					//on the top div
					if(!$scope.openTokData.expert){
						$("#publisherDiv").append("<div id='temp_pub_div'></div>");
						$scope.session.subscribe(streams[i], 'temp_pub_div');
					}
				}else{
					//If session is not one to many, subscribe and display the video in bottom div
					$("#subscriberDiv").append("<div id='temp_sub_div'></div>");
					$scope.session.subscribe(streams[i], 'temp_sub_div');
				}
			}
		}
	}
	
	function exceptionHandler(event){
		 TB.log(event.message);
		alert('in exception event'+event.code);
	}

	//============== File Uploading Part Started ============= 
	//============== DRAG & DROP =============
	var dropbox = document.getElementById("dropbox");
    $scope.dropText = 'Drop files here to upload...';
    $scope.newFiles = [];
    
 // init event handlers
    function dragEnterLeave(evt) {
        evt.stopPropagation();
        evt.preventDefault();
        $scope.$apply(function(){
            $scope.dropText = 'Drop files here...'
            $scope.dropClass = ''
        })
    }
    dropbox.addEventListener("dragenter", dragEnterLeave, false)
    dropbox.addEventListener("dragleave", dragEnterLeave, false)
    dropbox.addEventListener("dragover", function(evt) {
        evt.stopPropagation()
        evt.preventDefault()
        var clazz = 'not-available'
        var ok = evt.dataTransfer && evt.dataTransfer.types && evt.dataTransfer.types.indexOf('Files') >= 0
        $scope.$apply(function(){
            $scope.dropText = ok ? 'Drop files here...' : 'Only files are allowed!'
            $scope.dropClass = ok ? 'over' : 'not-available'
        })
    }, false)
    dropbox.addEventListener("drop", function(evt) {
        console.log('drop evt:', JSON.parse(JSON.stringify(evt.dataTransfer)))
        evt.stopPropagation()
        evt.preventDefault()
        $scope.$apply(function(){
            $scope.dropText = 'Drop files here...'
            $scope.dropClass = ''
        })
        
        var files = evt.dataTransfer.files
        if (files.length > 0) {
            $scope.$apply(function(){
                $scope.files = []
                for (var i = 0; i < files.length; i++) {
                    $scope.files.push(files[i])
                }
            })
        }
    }, false)
    
    //============== DRAG & DROP =============
    
    $scope.setFiles = function(element) {
    $scope.$apply(function(scope) {
      console.log('files:', element.files);
      // Turn the FileList object into an Array
        $scope.files = []
        for (var i = 0; i < element.files.length; i++) {
          $scope.files.push(element.files[i])
        }
      $scope.progressVisible = false
      });
    };

    $scope.uploadFile = function() {
        var fd = new FormData()
        for (var i in $scope.files) {
            fd.append("uploadedFile"+i, $scope.files[i])
        }
        
        /*$.ajax({
            url: 'uploadFile',
            data: fd,
            processData: false,
            contentType: 'multipart/form-data',
            type: 'POST',
            success: function ( data ) {
            	var responseFiles = eval(evt.target.responseText);
                for(var file in responseFiles){
                	$scope.newFiles.push(responseFiles[file]);
                }
                $rootScope.$broadcast('fileUploaded');
            }
        });*/
        var xhr = new XMLHttpRequest()
        xhr.upload.addEventListener("progress", uploadProgress, false)
        xhr.addEventListener("load", uploadComplete, false)
        xhr.addEventListener("error", uploadFailed, false)
        xhr.addEventListener("abort", uploadCanceled, false)
        xhr.open("POST", 'counsel/'+$scope.id+"/uploadFile")
        $scope.progressVisible = true;
        xhr.send(fd)
    }

    function uploadProgress(evt) {
        $scope.$apply(function(){
            if (evt.lengthComputable) {
                $scope.progress = Math.round(evt.loaded * 100 / evt.total)
            } else {
                $scope.progress = 'unable to compute'
            }
        })
    }

    function uploadComplete(evt) {
        /* This event is raised when the server send back a response */
        var responseFiles = eval(evt.target.responseText);
        for(var file in responseFiles){
        	$scope.newFiles.push(responseFiles[file]);
        }
        $rootScope.$broadcast('fileUploaded');
    }

    $rootScope.$on('fileUploaded', function(){
    	for(var file in $scope.newFiles){
    		$scope.uploadedFiles.push($scope.newFiles[file]);
    		firebaseFiles.push({fileName : $scope.newFiles[file].fileName, url : $scope.newFiles[file].fileUrl});
    	}
    	$scope.newFiles = [];
    	$scope.files = [];
    	$scope.$apply();
    })
    
    function uploadFailed(evt) {
        alert("There was an error attempting to upload the file.")
    }

    function uploadCanceled(evt) {
        $scope.$apply(function(){
            $scope.progressVisible = false
        })
        alert("The upload has been canceled by the user or the browser dropped the connection.")
    }
		  
}
opentokCtrl.$inject = ['$scope','$stateParams','$http','$location','$rootScope','uploadManager'];//inject required
